package com.hncc.dms.mq;

import com.hncc.mq.OrderMessage;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 消息消费者，异步回调，需要在回调方法中调用具体的业务类执行订单过期操作
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/9/6.
 */
@Component
@RabbitListener(queues = "his.order.cancel")
@Slf4j
@RequiredArgsConstructor
public class OrderMessageReceiver {
    private final MqOrderConfigProperties mqOrderConfigProperties;

    /**
     * 异步收取订单消息，修改订单状态为已过期
     * 订单主要有5类
     * @see com.hncc.mq.FeeType
     * @param orderMessage 订单消息对象
     */
    @RabbitHandler
    public void onMessage(OrderMessage orderMessage) {
        String receiveDateTime = DateUtils.parseDateToStr("yy.MM.dd HH:mm:ss", new Date());
        String createTime = DateUtils.parseDateToStr("yy.MM.dd HH:mm:ss", orderMessage.getCreateTime());
        log.info("创建时间：{}，收到时间：{}，消息内容：{}", createTime, receiveDateTime, orderMessage);
        int count = 0;
        try {
            count = expireOrder(orderMessage);
        } catch (Exception e) {
            log.error("取消订单失败:{}",orderMessage);
            log.error(e.getMessage(), e);
        }
        log.info("成功处理{}条消息", count);
    }

    /**
     * 过期订单
     * @param orderMessage
     * @return
     */
    private int expireOrder(OrderMessage orderMessage) {
        MqOrderConfig configBean = this.mqOrderConfigProperties.getProperties().get(orderMessage.getFeeType().getName());
        IExpireOrderService expireOrderService = SpringUtils.getBean(configBean.getServiceBeanId());
        return expireOrderService.expire(orderMessage.getOrderId());
    }

}
